<?php
/**
 * 共通功能类
 * User: Administrator
 * Date: 2017/8/18
 * Time: 11:25
 */
namespace backend\controllers;
use Yii;
use yii\web\UploadedFile;
use yii\web\AdminController;
use backend\models\UploadForm;

class CommonController extends AdminController{

    /**********************************************
     * 上专图片通用方法
     * 前端通过表单提交
     * 后端返回上传后的/upload开始的路径。
     * 显示图片是，拼接配置项中的图片二级域名
     **********************************************/
    public function actionImgUpload(){
        $model = new UploadForm();
        if (Yii::$app->request->isPost) {
            try{
                $model->img_url = UploadedFile::getInstance($model, 'img_url');
                $img_url = $model->upload();

            }catch(\Exception $e){
                //add by allen.qiang 20180112 异常处理，日志优化 start
                error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
                //add by allen.qiang 20180112 异常处理，日志优化 end
                $this->retJson($e->getMessage(),500);
            }

            if ($img_url == false){
                $this->retJson('上传文件出错!',500);
            }else{
                $this->retJson($img_url,200);
            }
        }

    }
    
    public function actionXheditUpload(){
        $result = array('err'=>'','msg'=>'');
		$model = new UploadForm();
        try{
            if (Yii::$app->request->isPost){

				try{

					$data = file_get_contents("php://input");						//临时文件流信息
					$model->img_url = new UploadedFile(); 							//实例化对象
					$bath_path = BASE_PATH;
					$rootPath = "uploads/"; //定义上传的根目录
					$randName = time() . rand(1000, 99999) . ".tmp"; 				//重新编译文件名称
					$path = date('Y-m-d',time());
					$rootPath = $rootPath . $path . "/";    						//拼接
					$bath_path = $bath_path . 'public/' . $rootPath;
					if (!file_exists($bath_path)){  							 	//判断该目录是否存在
						mkdir($bath_path,true);
						chmod($bath_path,0777);
					}
					$bool = file_put_contents($bath_path.$randName, $data);
					if($bool){
						preg_match('/\.[^\.]+$/',$_SERVER['HTTP_CONTENT_DISPOSITION'],$fileExt);///filename="*.+"/
						$fileName = substr($_SERVER['HTTP_CONTENT_DISPOSITION'],strripos($_SERVER['HTTP_CONTENT_DISPOSITION'],'filename="')+10,-1);
						$model->img_url->name		= $fileName;											//临时文件名称
						$model->img_url->tempName	= $bath_path.$randName;								//临时文件
						$model->img_url->error		= UPLOAD_ERR_NO_FILE;

						$img_url = $model->upload();
						$img_url = $img_url;
						$result['msg'] = Yii::$app->params['imageBathUrl'].'/'.$img_url;

					}else{
						error_log('img_url = false');
						throw new \Exception('上传文件出错!');
					}

				}catch(\Exception $e){
                    //mod by allen.qiang 20180112 异常处理，日志优化 start
					//error_log($e->getMessage());
                    error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
                    //mod by allen.qiang 20180112 异常处理，日志优化 end
					$this->retJson($e->getMessage(),500);
				}
            }
        }catch(\Exception $e){
            $result['err'] = $e->getMessage();
            $result['msg'] = '';
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
        }
        return json_encode($result);
    }

    public function actionImgsUpload(){
        $model = new UploadForm();
        if (Yii::$app->request->isPost){
            try{
                $model->img_url = UploadedFile::getInstances($model, 'img_url');
                $img_url = $model->uploads();
            }catch(\Exception $e){
                //mod by allen.qiang 20180112 异常处理，日志优化 start
                //error_log($e->getMessage());
                error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
                //mod by allen.qiang 20180112 异常处理，日志优化 end
                $this->retJson($e->getMessage(),500);
            }

            if ($img_url == false){
                //mod by allen.qiang 20180112 异常处理，日志优化 start
                //error_log('img_url = false');
                error_log('error->' . __METHOD__ . ' error:img_url = false');
                //mod by allen.qiang 20180112 异常处理，日志优化 end
                $this->retJson('上传图片出错!',500);
            }else{
                $this->retJson($this->imageTool($img_url),200);
            }
        }
    }

    //layer相册
    public function imageTool($data){
        $base_array = array(
            'title'=>'',
            'id'=>1,
            'start'=>0,
            'data'=>array()
        );

        foreach($data as $key=>$value){
            $base_array['data'][$key]['alt'] = '';
            $base_array['data'][$key]['pid'] = $key;
            $base_array['data'][$key]['src'] = Yii::$app->params['imageBathUrl'].'/'. $value;
            $base_array['data'][$key]['thumb'] = '';
        }

        return $base_array;
    }
    
    /**
     * 接收日志保存
     */
    public function actionTrack(){
        if(isset(Yii::$app->request->queryString)){
            $this->saveWebLog();
        }
        //error_log(print_r( explode('&',Yii::$app->request->queryString),1));
    }
    
    /**
     * 网站日志保存
     */
    private function saveWebLog(){
        try{
            $log_web['ip'] = Yii::$app->getRequest()->userIP;                        //IP地址
            $log_web['session_id'] = Yii::$app->request->get('session_id');     //访客标识
            $log_web['url'] = Yii::$app->request->get('access_url');             //访问网址
            $log_web['referer_url'] = Yii::$app->request->get('referer_url');   //上一页
            $log_web['user_name'] = Yii::$app->request->get('user_name');        //会员登录id
            $log_web['browser'] = Yii::$app->request->get('userAgent');          //浏览器
            $log_web['device'] = Yii::$app->request->get('device');               //设备
            $log_web['tracker_code'] = Yii::$app->request->get('tracker_code'); //追踪代码
            $log_web['key1'] = Yii::$app->request->get('key1');                    //推广类型
            $log_web['key2'] = Yii::$app->request->get('key2');                    //第二分类
            $log_web['key3'] = Yii::$app->request->get('key3');                    //第三分类
            $log_web['screen_resolution'] = Yii::$app->request->get('screen_resolution');//屏幕分辨率
            $log_web['source_type'] = Yii::$app->request->get('source_type');   //来源类型
            
            $ret = Yii::$app->db->createCommand()->insert('j_log_web',$log_web)->execute();
            if(!$ret){
                //mod by allen.qiang 20180112 异常处理，日志优化 start
                //error_log('网站日志保存失败！');
                error_log('error->' . __METHOD__ . ' error:网站日志保存失败！');
                //mod by allen.qiang 20180112 异常处理，日志优化 end
            }
        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log('日志保存失败！ error:' . $e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
        }
        
    }

    //打印日志
    function elog ($obj = null, $path = null)
    {
        if(is_array($obj) || is_object($obj))
            $obj = print_r($obj,1);
        elseif($obj === null) {
            if(!isset($GLOBALS["logIndex"])) $GLOBALS["logIndex"] = 1;
            $obj = 'LOG--------------- '.$GLOBALS["logIndex"];
            $GLOBALS["logIndex"]++;
        }
        $path ? error_log($obj, 3, $path) : error_log($obj);
    }
}

